package com.hsogoo.study.concurrency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by za-huangsaigang on 2018/8/28.
 */
public class AtomicIntegerWithLock {

    private int  value;
    private Lock lock = new ReentrantLock();

    public AtomicIntegerWithLock() {
        super();
    }

    public AtomicIntegerWithLock(int value) {
        this.value = value;
    }

    public int get(){
        lock.lock();
        try{
            return value;
        }finally {
            lock.unlock();
        }
    }

    public void set(int newValue){
        lock.lock();
        try{
            this.value = newValue;
        }finally {
            lock.unlock();
        }
    }

    public int getAndSet(int newValue){
        lock.lock();
        try{
            int ret = value;
            value = newValue;
            return ret;
        }finally {
            lock.unlock();
        }
    }

    public boolean compareAndSet(int expect, int update) {
        lock.lock();
        try{
            if(this.value == expect){
                this.value = update;
                return true;
            }
            return false;
        }finally {
            lock.unlock();
        }
    }

    public int getAndIncrement(){
        lock.lock();
        try{
            return value++;
        }finally {
            lock.unlock();
        }
    }

    public int getAndDecrement(){
        lock.lock();
        try{
            return value--;
        }finally {
            lock.unlock();
        }
    }

    public int incrementAndGet(){
        lock.lock();
        try{
            return ++value;
        }finally {
            lock.unlock();
        }
    }

    public int decrementAndGet(){
        lock.lock();
        try{
            return --value;
        }finally {
            lock.unlock();
        }
    }

    public int getAndAdd(int delta){
        lock.lock();
        try{
            int ret = value;
            value += delta;
            return ret;
        }finally {
            lock.unlock();
        }
    }

    public int addAndGet(int delta){
        lock.lock();
        try{
            value += delta;
            return value;
        }finally {
            lock.unlock();
        }
    }

}
